package com.longcai.service.impl.clyjuser;


import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.entity.customer.ClyjUserProperty;
import com.longcai.entity.customer.ClyjUserTouch;
import com.longcai.mapper.clyjuser.ClyjUserMapper;
import com.longcai.mapper.clyjuser.ClyjUserTouchMapper;
import com.longcai.mapper.property.ClyjUserPropertyMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.clyjuser.ClyjUserService;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author M
 * @since 2019-03-31
 */
@Service
public class ClyjUserServiceImpl extends ServiceImpl<ClyjUserMapper, ClyjUser> implements ClyjUserService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjUserMapper clyjUserMapper;
    @Autowired
    private ClyjUserPropertyMapper clyjUserPropertyMapper;
    
    @Autowired
    private ClyjUserTouchMapper clyjUserTouchMapper;
    
    /**
     * 获取会员列表
     *
     * @param clyjUser
     * @param pageHelper
     * @return
     */
    @Override
    public PageTableResponse userList(ClyjUser clyjUser, PageHelper pageHelper) {
        //分页
        Page<ClyjUser> page = new Page<ClyjUser>(pageHelper.getStart(), pageHelper.getLength());
        /**查询条件筛选**/
        QueryWrapper<ClyjUser> queryWrapper=query(clyjUser);
        IPage<ClyjUser> sysRoleIPage = this.clyjUserMapper.selectPage(page, queryWrapper);
        List<ClyjUser> records = sysRoleIPage.getRecords();
        if(records!=null&&records.size()>0){
        	for (ClyjUser clyjUsers : records) {
        		String userId=clyjUsers.getUserId();
        		 /**0,查看 页面     1,授权页面**/
        		if(!StringUtils.isEmpty(clyjUser.getQueryType())&&clyjUser.getQueryType().equals("0")){
        			ClyjUserProperty clyjUserProperty=clyjUserPropertyMapper.selectById(userId);
    	    		if(clyjUserProperty!=null){
    	    			clyjUsers.setIntegral(clyjUserProperty.getIntegral());//积分
    	    			clyjUsers.setShoestringMoney(clyjUserProperty.getShoestringMoney());//零钱
    	    		}
        		}else if(!StringUtils.isEmpty(clyjUser.getQueryType())&&clyjUser.getQueryType().equals("1")){
    	    		/***团队人数--个人销量----团队销量**/
        			QueryWrapper<ClyjUserTouch> queryWrapper1=new QueryWrapper<ClyjUserTouch>();
        			queryWrapper1.eq("user_p_id", userId);
        			int teamNumber=clyjUserTouchMapper.selectCount(queryWrapper1); /**团队人数**/
        			clyjUsers.setTeamNumber(teamNumber);/**团队人数**/
        			queryWrapper1.eq("status", "2");/****状态（1：临时推荐人；2：永久推荐人）***/
        			queryWrapper1.eq("relation_level", "0");//0  直接推荐人
        			List<ClyjUserTouch> personalSaleList=clyjUserTouchMapper.selectList(queryWrapper1); /**个人销量**/
        			int persionCount=0;//个人销量
        			int teamCount=0;//团队销量
        			if(personalSaleList!=null&&personalSaleList.size()>0){
        				persionCount=personalSaleList.size();
        				clyjUsers.setPersonalSale(personalSaleList.size());
        				for (ClyjUserTouch clyjUserTouch : personalSaleList) {
        					String userIds=clyjUserTouch.getUserId();//团队的每个人数
        					QueryWrapper<ClyjUserTouch> query=new QueryWrapper<ClyjUserTouch>();
        					queryWrapper1.eq("user_p_id", userIds);
        					queryWrapper1.eq("status", "2");/****状态（1：临时推荐人；2：永久推荐人）***/
        					queryWrapper1.eq("relation_level", "0");//0  直接推荐人
        					teamCount=clyjUserTouchMapper.selectCount(query);
        					teamCount+=teamCount;
        				}
        				clyjUsers.setTeamSale(teamCount);
        			}
        			Integer level=clyjUsers.getLevel();//等级（0 普通会员, 1 导师 2 讲师 3 经理）
        			/**IsReachTheStandard  是否达标 0,达标      1,不达标**/
        			if(level==1){
        				if(persionCount>=10&&teamCount>=60){
        					clyjUsers.setIsReachTheStandard("0");
        				}else{
        					clyjUsers.setIsReachTheStandard("1");
        				}
        			}else if(level==2){
        				if(persionCount>=30&&teamCount>=600){
        					clyjUsers.setIsReachTheStandard("0");
        				}else{
        					clyjUsers.setIsReachTheStandard("1");
        				}
        			}
        			
        		}
        	}
        }
        PageTableResponse pageTableResponse = new PageTableResponse(records.size(),
        		records.size(), records);
        return pageTableResponse;
    }
    
    /**查询条件拼接**/
    public QueryWrapper<ClyjUser> query(ClyjUser clyjUser){
    	QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(clyjUser.getUsername())) {
            queryWrapper.like("username", clyjUser.getUsername());
        }
        if (!StringUtils.isEmpty(clyjUser.getPhone())) {
            queryWrapper.like("phone", clyjUser.getPhone());
        }
        /**授权页面，只展示导购以上的信息**/
        if(!StringUtils.isEmpty(clyjUser.getQueryType())){
        	if(clyjUser.getLevel()!=null){
        		queryWrapper.ge("level",clyjUser.getLevel() );
        	}
        }
        /** 等级（0 普通会员, 1 导师 2 讲师 3 经理）**/
        if(!StringUtils.isEmpty(clyjUser.getLevel())){
        	queryWrapper.eq("level", clyjUser.getLevel());
        }
      
    	/**开启状态（0开启  1，未开启**/
        if(!StringUtils.isEmpty(clyjUser.getOpenState())){
        	queryWrapper.eq("openState", clyjUser.getOpenState());
        }
        Date leftTime=clyjUser.getLeftTime();
        Date rightTime=clyjUser.getRightTime();
        if(leftTime!=null&&!leftTime.equals("")){
        	queryWrapper.between("create_time", leftTime, new Date());
        }
        if(rightTime!=null&&!rightTime.equals("")){
        	queryWrapper.between("create_time", leftTime, new Date());
        }
        if(leftTime!=null&&!leftTime.equals("")&&rightTime!=null&&!rightTime.equals("")){
        	queryWrapper.between("create_time", leftTime, rightTime);
        }
		return queryWrapper;
    }

    /**
     * 根据id获取会员信息
     *
     * @param id
     * @return
     */
    @Override
    public ApiResult getById(String id) {
        try {
            QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", id);
            ClyjUser clyjUser = this.clyjUserMapper.selectOne(queryWrapper);
            logger.debug("查询成功++++++++++", clyjUser);
            return ApiResult.success(clyjUser);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 修改会员信息
     *
     * @param clyjUser
     * @return
     */
    @Override
    public Integer updateUser(ClyjUser clyjUser) {
        try {
            Integer integer = this.clyjUserMapper.updateById(clyjUser);
            logger.debug("修改成功++++++++++", integer);
            return integer;
        } catch (Exception e) {
            logger.error("修改失败+++++");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    public void delClyjUser(String id) {
        try {
            this.clyjUserMapper.deleteById(id);
            logger.debug("删除成功+++++++++", id);
        } catch (Exception e) {
            logger.error("删除失败+++++++++++", id);
            e.printStackTrace();
        }
    }

    /**
     * 根据名称查询用户信息
     *
     * @param name
     * @return
     */
    @Override
    public ClyjUser getName(String name) {
        try {
            QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", name);
            ClyjUser clyjUser = this.clyjUserMapper.selectOne(queryWrapper);
            logger.debug("查询{}", clyjUser);
            return clyjUser;
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
        }
        return null;
    }

    /**更改用户开启状态**/
	@Override
	public int changeUserState(String userId, String openState) {
		int a=clyjUserMapper.checkUserState(userId,openState);
		return a;
	}

	/***
	 * 根据用户Id查询用户信息
	 */
	@Override
	public ClyjUser selectUser(String userId) {
		ClyjUser clyjUser=clyjUserMapper.selectById(userId);
		if(clyjUser!=null){
			/**积分   ----零钱----余额**/
			ClyjUserProperty clyjUserProperty=clyjUserPropertyMapper.selectById(userId);
    		if(clyjUserProperty!=null){
    			clyjUser.setIntegral(clyjUserProperty.getIntegral());//积分
    			clyjUser.setShoestringMoney(clyjUserProperty.getShoestringMoney());//零钱
    			clyjUser.setAccount(clyjUserProperty.getAccount());//余额
    		}
    		/***团队人数--个人销量----团队销量**/
			QueryWrapper<ClyjUserTouch> queryWrapper=new QueryWrapper<ClyjUserTouch>();
			queryWrapper.eq("user_p_id", userId);
			int teamNumber=clyjUserTouchMapper.selectCount(queryWrapper); /**团队人数**/
			clyjUser.setTeamNumber(teamNumber);/**团队人数**/
			queryWrapper.eq("status", "2");/****状态（1：临时推荐人；2：永久推荐人）***/
			queryWrapper.eq("relation_level", "0");//0  直接推荐人
			List<ClyjUserTouch> personalSaleList=clyjUserTouchMapper.selectList(queryWrapper); /**个人销量**/
			int count=0;//团队销量
			if(personalSaleList!=null&&personalSaleList.size()>0){
				clyjUser.setPersonalSale(personalSaleList.size());
				for (ClyjUserTouch clyjUserTouch : personalSaleList) {
					String userIds=clyjUserTouch.getUserId();//团队的每个人数
					QueryWrapper<ClyjUserTouch> query=new QueryWrapper<ClyjUserTouch>();
					queryWrapper.eq("user_p_id", userIds);
					queryWrapper.eq("status", "2");/****状态（1：临时推荐人；2：永久推荐人）***/
					queryWrapper.eq("relation_level", "0");//0  直接推荐人
					count=clyjUserTouchMapper.selectCount(query);
					count+=count;
				}
				clyjUser.setTeamSale(count);
			}
			return clyjUser;
		}
		return null;
	}
}








